package com.fdd.furns.web;

import com.fdd.furns.pojo.Member;
import com.fdd.furns.service.MemberService;
import com.fdd.furns.service.impl.MemberServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/registerServlet")
public class RegisterServlet extends HttpServlet {
    private MemberService memberService = new MemberServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");

        if (!memberService.isExist(username)) {//用户名不存在，可以注册
            Member member = new Member(0, username, password, email);
            if (memberService.registerMember(member)) {
                req.getRequestDispatcher("/views/member/register_ok.jsp").forward(req, resp);
            } else {
                req.getRequestDispatcher("/views/member/register_fail.jsp").forward(req, resp);
            }
        } else {//用户名存在，不能注册
            System.out.println("用户名存在，不能注册");
            req.setAttribute("error", "用户名已存在，请重新注册");
            req.getRequestDispatcher("/views/member/login.jsp").forward(req, resp);


        }
    }
}
